@(mapSize: String)

@main("PUC TowerDefence - The game") {
    @navbar("menu2")


    <div class="container">
            <!-- Main hero unit for a primary marketing message or call to action -->
        <div class="jumbotron">

            <div id="initLoading">
                  <h2>loading...</h2>
            </div>

            <div id="gameWindow">


                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h3 class="panel-title">Game status</h3>
                    </div>
                    <div id="gamestats" class="panel-body">

                    </div>
                </div>

                <div id="gameover" class="panel panel-default">
                    <div class="panel-heading"><h2>Nice you killed <span id="monsterscore"></span> monsters and reached wave <span id="wavescore"></span>.</h2></div>
                    <div class="panel-body">
                        <p>Login with Google to save your highscore!!!</p>
                        <a href="/openID/auth">
                            <img src="/assets/images/sign-in-with-google.png">
                        </a>
                    </div>
                </div>

                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h3 class="panel-title">Map</h3>
                    </div>
                    <div id="gamemap" class="panel-body table-responsive">

                    </div>

                </div>

                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h3 class="panel-title">Control Panel</h3>
                    </div>
                    <div id="gamebuttons" class="panel-body">
                        <div class="row">
                            <button type="button" id="small" class="btn btn-default" >Build Small Tower (20 Gold)</button>
                            <button type="button" id="middle" class="btn btn-default" >Build Middle Tower (70 Gold)</button>
                            <button type="button" id="big" class="btn btn-default" >Build Big Tower (150 Gold)</button>
                            <button type="button" id="update" class="btn btn-default" >Update Tower</button>
                            <button type="button" id="next" class="btn btn-default" >Next Wave</button>
                        </div>
                    </div>
                <div id="gameexceptionalert" class="alert alert-danger">
                    <strong>Oh snap!</strong> Change a few things up and try submitting again.
                </div>
                </div>




            </div>
        </div>

       <hr>

        <footer>
            <p>©PUC Production Studios - Finest Software Development 2014</p>
        </footer>

    </div>

    <script type="text/javascript" charset="utf-8">
        // Shorthand for $( document ).ready()
        $(function() {

            <!-- Websocket Connection -->
            //var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket
            socketurl = "@routes.Application.websocketConnection(mapSize).webSocketURL(request)"
            // var socket = new WS(socketurl)
            socket = new WebSocket(socketurl);
            var initialized = false

            var x = 0;
            var y = 0;
            var rdyForUpdate = true;
            var lastLive = 7;
            // incomming messages
            var receiveEvent = function(event) {
                var data = JSON.parse(event.data)

            // map update
            if(data.kind =='GameUpdate' && rdyForUpdate == true){

            rdyForUpdate = false;

                if( data.gameover){
                    $("#monsterscore").html((data.monster))
                    $("#wavescore").html((data.wave))
                    $("#gameover").fadeIn()
                    //$("#gamemap" ).effect( "explode", { pieces : 9 }, 10000 );

                } else {

                    // remove monsters and towers
                    $(".monster").fadeOut(250 )
                    $(".monster").delay(250 ).remove()
                    $(".tower").remove()

                    // game stats
                    // Formatter stats = new Formatter().format("GameOver: %b |Wave: %-2d | Gold: %5d | Live: %2d | Seconds to the next Spawn: %2d ", map.getGameOver(), map.getMonstersSpawned(), map.getGold(), map.getLive(), map.getSecondsToNextSpawn().getSeconds());
                    var statsdata = "Wave: " + data.wave + " | Gold: "+data.gold+" | Live: "+data.live+" | Seconds to the next Spawn: "+data.secondstospawn;
                    $("#gamestats").html(statsdata)

                    if(lastLive > data.live){
                        lastLive = data.live;
                       // $("#gamemap" ).effect( "shake" );
                        $("#gamemap" ).effect( "bounce" );
                    }

                    // set the monsters and towers
                    $.each(data.updatesarray, function(index, value){

                    selector1 = '#gamemap .mapspan[alt="x=' + value.x + ' y=' + value.y + '"]';
                    $(selector1).append(value.html)

                    });
                }
            rdyForUpdate = true;
            return

            }

                // kind tester
                //$("#gameWindow" ).append(data.kind);

                // remove loading init
                // Websocket ready
                $("#initLoading").fadeOut(500, function(){
                    $("#gameWindow").fadeIn(1000)
                })

                // Handle errors
                if(data.error) {
                    socket.close()
                    // TODO Show Error
                    //alert(data.error)

                    return
                }

                // map init
                if(data.kind =='GameInitialisation' && !initialized){
                    // map
                    $("#gamemap").html(data.mapdata)
                    initClick()
                    initialized = true

                }



                // game exception
                if(data.kind =='GameException'){
                    $("#gameexceptionalert").html(data.message)
                    // fade in, pause and fade out

                    $("#gameexceptionalert").fadeIn().effect( "shake" ).delay(3000 ).fadeOut();
                }
            }


            // on message
            socket.onmessage = receiveEvent

            // if errors on websocket
            var onalert = function(event) {
                //alert("alert" + event);
            }

            socket.onerror = onalert;
            socket.onclose = onalert;

            // map click
            function initClick(){
                $("#gamemap .mapspan").on( "click", function(){
                    x = $(this ).attr("x");
                    y = $(this ).attr("y");

                    $("#gamemap .selected").removeClass("selected");
                    $( this ).addClass("selected");

                });
            }


            // client -> Server
            function sendCommandNextWave() {
                socket.send(JSON.stringify(
                    {
                        kind: "Command",
                        command: "NextWave"
                    }
                ))
            }


            function sendCommandBuildTower(posX, posY, towerSize) {
                socket.send(JSON.stringify(
                {
                    kind: "Command",
                    command: "BuildTower",
                    posx: posX,
                    posy: posY,
                    towersize: towerSize
                }
                ))
            }

            function sendCommandUpdateTower(posX, posY) {
                socket.send(JSON.stringify(
                {
                    kind: "Command",
                    command: "UpdateTower",
                    posx: posX,
                    posy: posY
                }
                ))
            }

            // controllpannel

            $("#next").click(sendCommandNextWave)
            $("#small").click(function(){
                sendCommandBuildTower(x, y, "0")
            })
            $("#middle").click(function(){
                sendCommandBuildTower(x, y, "1")
            })
            $("#big").click(function(){
                sendCommandBuildTower(x, y, "2")
            })
            $("#update").click(function(){
                sendCommandUpdateTower(x, y)
            })

        })

    </script>

}